package interview;

import java.util.Currency;
import java.util.TreeMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class SharedResource {
    private Lock lock = new ReentrantLock();

    private Condition a = lock.newCondition();
    private Condition b = lock.newCondition();
    private Condition c = lock.newCondition();

    private int number = 0;

    public void printA() {
        lock.lock();
        try {
            // 判断
            while (number != 0) {
                try {
                    a.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活
//            System.out.println(Thread.currentThread().getName() + "\tA");
            System.out.print("A");
            // 唤醒b
            number = 1;
            b.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printB() {
        lock.lock();
        try {
            // 判断
            while (number != 1) {
                try {
                    b.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活
//            System.out.println(Thread.currentThread().getName() + "\tB");
            System.out.print("B");
            // 唤醒c
            number = 2;
            c.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printC() {
        lock.lock();
        try {
            // 判断
            while (number != 2) {
                try {
                    c.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            // 干活
//            System.out.println(Thread.currentThread().getName() + "\tC");
            System.out.print("C");
            // 唤醒a
            number = 0;
            a.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

public class TakeTurn {
//    private static int count = 0;
    public static void main(String[] args) {
        SharedResource sharedResource = new SharedResource();
        new Thread(()->{
            for (int i= 0; i < 5; i++) {
                sharedResource.printA();
            }
        }, "1").start();

        new Thread(()->{
            for (int i= 0; i < 5; i++) {
                sharedResource.printB();
            }
        }, "2").start();

        new Thread(()->{
            for (int i= 0; i < 5; i++) {
                sharedResource.printC();
            }
        }, "3").start();
    }
}
